package com.gientech.madp.sm2.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.*;

/**
 * json序列化工具
 *
 * @Author smile_ZhongXuan
 * @Date 2021/10/8 10:12
 * @Version 1.0
 */
public class FopJsonUtil {
	public static Map<String, String> getSortedMap(String body) {
		Map<String, String> sortedParams = new TreeMap<String, String>();
		Map<String, String> params =
				JSONObject.parseObject(body, new TypeReference<Map<String, String>>() {
				});
		sortedParams.putAll(params);
		return sortedParams;
	}

	/**
	 * json数据按ascii排序-多层json
	 * @param sortedParams json-Map<String, Object>
	 * @return
	 */
	public static String getSignContents(Map<String, Object> sortedParams) {
		StringBuffer content = new StringBuffer();
		List<String> keys = new ArrayList<String>(sortedParams.keySet());
		Collections.sort(keys);
		int index = 0;
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			Object values = sortedParams.get(key);
			String value = null;
			if(values instanceof Map){
				Map<String,Object> map = (Map<String, Object>) values;
				value = JSONUtil.toJsonStr(getAscString(map));
			}else {
				value = values.toString();
			}
			if (areNotEmpty(key, value)) {
				content.append((index == 0 ? "" : "&") + key + "=" + value);
				index++;
			}
		}
		return content.toString().replaceAll(" ","");
	}

	/**
	 * 对json数据按ASCII码进行排序，返回格式化后的json数据
	 * 第一层使用&符号，第二层之后的json数据保持原有格式，但是要对json中的键值排序
	 * pswdTp=01&reqHead={"chnlGrpCd":"100","cnsmrChnlTpCd":"","cnsmrSeqNo":"","cnsmrSysId":"305105","eventNo":"","lglPrsnCd":"9999","mac":"","orgId":"087190007","origIttAplNo":"100200","pageIndex":"","pageSize":"","svcCd":"AsCapGetRandom","svcScn":"01","txnChnlTp":"105","txnDt":"2021/09/18","txnTlrId":"MPB00001","txnTm":"","txnTmlId":"","vrsn":"1.0.0"}
	 * @param jsonMap
	 * @return
	 */
	public static Object getAscString(Map<String, Object> jsonMap) {
		List<String> keys = new ArrayList<String>(jsonMap.keySet());
		Collections.sort(keys);
		LinkedHashMap<String, Object> map=new LinkedHashMap<String, Object>();
		for(int i=0;i<keys.size();i++){
			String key = keys.get(i);
			Object value = jsonMap.get(key);
			Object valueString;
			if(StrUtil.isNotEmpty(keys.get(i))){
				if (value instanceof String) {
					valueString = (String) value;
					map.put(key, valueString);
				} else if (value instanceof Map){
					valueString = getAscString((Map<String, Object>) value);
					map.put(key, valueString);
				} else {
//					valueString = JSONObject.toJSONString(value, SerializerFeature.MapSortField);
					map.put(key, value);
				}
			}
		}
		return JSONUtil.parseObj(map);
	}

	/**
	 * 检查指定的字符串列表是否不为空。
	 */
	public static boolean areNotEmpty(String... values) {
		boolean result = true;
		if (values == null || values.length == 0) {
			result = false;
		} else {
			for (String value : values) {
				result &= !isEmpty(value);
			}
		}
		return result;
	}

	public static boolean isEmpty(String value) {
		int strLen;
		if (value == null || (strLen = value.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if ((Character.isWhitespace(value.charAt(i)) == false)) {
				return false;
			}
		}
		return true;
	}


	public static String getSignatureParameters(Map<String, Object> signatureParameters) {
		StringBuilder stringBuilder = new StringBuilder();
		ArrayList<String> keys = new ArrayList<>(signatureParameters.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			Object value = signatureParameters.get(key);
			String valueString;
			if (value instanceof String) {
				valueString = (String) value;
			} else if (value instanceof Map){
				valueString = getSignatureParameters((Map<String, Object>) value);
			} else {
				valueString = JSONObject.toJSONString(value, SerializerFeature.MapSortField);
			}
			stringBuilder.append(key).append("=").append(valueString);
			if (i != keys.size() - 1) {
				stringBuilder.append("&");
			}
		}
		return stringBuilder.toString();
	}

	public static String getSignature(Map<String, Object> signatureParameters) {
		String text = getSignatureParameters(signatureParameters);
		System.out.println("text： " + text);
		return SHA256Utils.getSHA256(text);
	}


	public static Map<String, String> getSortedMapByKey(String body) {
		Map<String, String> params =
				JSONObject.parseObject(body, new TypeReference<Map<String, String>>() {
				});
		return map2SortMap(params);
	}

	public static Map<String, String> map2SortMap(Map<String, String> params){
		Map<String, String> sortedParams = new TreeMap<String, String>();
		sortedParams.putAll(params);
		return sortedParams;
	}

	public static String getSignContent(Map<String, String> sortedParams) {
		StringBuffer content = new StringBuffer();
		List<String> keys = new ArrayList<>(sortedParams.keySet());
		Collections.sort(keys);
		int index = 0;
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = sortedParams.get(key);
			if (areNotEmpty(key, value)) {
				content.append((index == 0 ? "" : "&") + key + "=" + value.trim());
				index++;
			}
		}
		return content.toString();
	}



}
